<template>
  <div class="container">
    <header class="app-header">
      <h1>Ollama 本地对话助手</h1>
      <p class="subtitle">简单、高效的本地 AI 对话体验</p>
    </header>

    <main class="chat-container">
      <div class="input-section">
        <label class="input-label" for="question-input">输入问题：</label>
        <div class="input-group">
          <input id="question-input" class="input" v-model="question" placeholder="请输入您的问题..." @keyup.enter="update" />
          <button class="submit-btn" @click="update">
            <span class="btn-text">发送</span>
          </button>
        </div>
      </div>

      <div class="settings-section">
        <label class="settings-label">
          <input type="checkbox" v-model="stream" />
          <span>实时流式输出</span>
        </label>
      </div>

      <div class="output-section">
        <div class="output-header">
          <h2>AI 回复</h2>
        </div>
        <div class="output-content">
          <!-- {{ rawContent || '等待您的输入...' }} -->
          <div>{{ thinkContent }}</div>
          <div v-html="replyContent"></div>
        </div>
      </div>
    </main>

    <footer class="app-footer">
      <p>连接本地 Ollama 服务</p>
    </footer>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { marked } from 'marked';

const question = ref('讲一个关于中国龙的故事');
const rawContent = ref('');
const stream = ref(true);

const update = async () => {
  if (!question) return;
  rawContent.value = "思考中...";

  const OLLAMA_API = import.meta.env.VITE_OLLAMA_API || 'http://localhost:11434';
  const MODEL_NAME = import.meta.env.VITE_OLLAMA_MODEL;

  const endpoint = `${OLLAMA_API}/api/generate`;
  const headers = {
    'Content-Type': 'application/json',
  };

  // console.log(question.value);
  const response = await fetch(endpoint, {
    method: 'POST',
    headers: headers,
    body: JSON.stringify({
      model: MODEL_NAME,
      prompt: question.value,
      stream: stream.value,
    })
  });

  if (stream.value) {
    const reader = response.body?.getReader();
    const decoder = new TextDecoder();
    let done = false;
    let buffer = '';
    rawContent.value = '';

    while (!done) {
      const { value, done: doneReading } = await (reader?.read());
      done = doneReading;
      const chunkValue = buffer + decoder.decode(value);
      buffer = '';

      const lines = chunkValue.split('\n').filter(Boolean);

      for (const line of lines) {
        try {
          const data = JSON.parse(line);
          const delta = data.response;
          if (delta) rawContent.value += delta;
        } catch (ex) {
          buffer += line;
        }
      }
    }
  } else {
    const data = await response.json();
    rawContent.value = data.response;
  }
}

const thinkContent = computed(() => {
  if (rawContent.value.startsWith('<think>')) {
    const match = rawContent.value.match(/^<think>([\s\S]*?)<\/think>/im);
    return match ? match[1] : rawContent.value.replace(/^<think>/, '');
  }
  return '';
});

const replyContent = computed(() => {
  let content = '';
  if (rawContent.value.startsWith('<think>')) {
    content = rawContent.value.split('</think>')[1] || '';
  } else {
    content = rawContent.value || '';
  }
  return marked(content);
});
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-size: 1rem;
}

.app-header {
  text-align: center;
  margin-bottom: 30px;
  color: var(--text-primary);
}

.app-header h1 {
  font-size: 2.2rem;
  margin-bottom: 8px;
  font-weight: 600;
  color: var(--accent-color);
}

.subtitle {
  font-size: 1rem;
  color: var(--text-secondary);
  margin: 0;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.input-section {
  margin-bottom: 10px;
}

.input-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: var(--text-primary);
}

.input-group {
  display: flex;
  gap: 10px;
}

.input {
  flex: 1;
  padding: 12px 16px;
  border: 2px solid var(--border-color);
  border-radius: 12px;
  font-size: 1rem;
  background-color: var(--input-bg);
  color: var(--text-primary);
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
}

.input:focus {
  outline: none;
  border-color: var(--accent-color);
  box-shadow: 0 0 0 3px rgba(100, 108, 255, 0.1);
}

.submit-btn {
  padding: 12px 24px;
  background-color: var(--accent-color);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s ease, transform 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.submit-btn:hover {
  background-color: var(--accent-hover);
  transform: translateY(-1px);
}

.submit-btn:active {
  transform: translateY(0);
}

.settings-section {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.settings-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  color: var(--text-secondary);
  font-size: 0.9rem;
}

.settings-label input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.output-section {
  flex: 1;
  background-color: var(--output-bg);
  border: 1px solid var(--border-color);
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.output-header {
  padding: 16px 20px;
  border-bottom: 1px solid var(--border-color);
  background-color: var(--output-header-bg);
}

.output-header h2 {
  margin: 0;
  font-size: 1.2rem;
  font-weight: 500;
  color: var(--text-primary);
}

.output-content {
  padding: 20px;
  min-height: 300px;
  line-height: 1.7;
  color: var(--text-primary);
  white-space: pre-wrap;
  word-break: break-word;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.app-footer {
  margin-top: 30px;
  text-align: center;
  padding: 10px 0;
  color: var(--text-secondary);
  font-size: 0.9rem;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .container {
    padding: 15px;
  }

  .app-header h1 {
    font-size: 1.8rem;
  }

  .input-group {
    flex-direction: column;
  }

  .submit-btn {
    width: 100%;
  }

  .output-content {
    min-height: 250px;
  }
}
</style>